package no.hig.imt4721.template;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import no.hig.imt4721.model.Repetition;
import no.hig.imt4721.model.Session;
import no.hig.imt4721.model.Subject;
import no.hig.imt4721.model.TemplateWithStandardDeviation;
import no.hig.imt4721.util.Statistics;

public class TemplateCreatorMeanWithStandardDeviation extends TemplateCreator
{	
	public TemplateCreatorMeanWithStandardDeviation(int sessionsToDisregard, int sessionsForTemplate, int repetitionsForTemplate)
	{
		super(sessionsToDisregard, sessionsForTemplate, repetitionsForTemplate);
	}
	
	public void calculate(List<Subject> subjects)
	{
		splitData(subjects);

		// Create template
		for(Subject subject : getTemplateData())
		{
			double[] sumOfValues = new double[subject.getSessions().get(0).getRepetitions().get(0).getLengthOfRow()];
			double numberOfValues = 0;
			
			for(Session session : subject.getSessions())
			{
				for(Repetition repetition : session.getRepetitions())
				{
					for(int i = 0; i < subject.getSessions().get(0).getRepetitions().get(0).getLengthOfRow(); i++)
					{
						sumOfValues[i] += repetition.getRowElement(i);
					}
					numberOfValues++;
				}
			}
			
			TemplateWithStandardDeviation template = new TemplateWithStandardDeviation();
			
			for(int i = 0; i < subject.getSessions().get(0).getRepetitions().get(0).getLengthOfRow(); i++)
			{
				template.addValue(sumOfValues[i] / numberOfValues);
			}			
			
			for(int i = 0; i < subject.getSessions().get(0).getRepetitions().get(0).getLengthOfRow(); i++)
			{
				List<Double> values = new ArrayList<Double>();
				
				for(Session session : subject.getSessions())
				{
					for(Repetition repetition : session.getRepetitions())
					{
						values.add(repetition.getRowElement(i));
					}
				}
				
				Collections.sort(values);
				
				double standardDeviation = Statistics.calculateStandardDeviation(values);
				template.addStandardDeviationValue(standardDeviation);
			}
			
			templates.add(template);
		}
	}
}
